package com.itheima;

import java.util.Scanner;

public class array3 {
    public static void main(String[] args) {
        System.out.println("请输入华容道长度：");
        Scanner sc = new Scanner(System.in);
        int number = sc.nextInt();
        array3(number);
    }
    public static void array3(int num) {
        int[][] arr = new int[num][num];
        int count = 1;
        System.out.println("打乱前的华容道：");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (i == num - 1 && j == num - 1) {
                    arr[i][j] = 0;
                } else {
                    arr[i][j] = count++;
                }
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
        // 打乱算法优化：只打乱非空格位置，避免自身交换
//        shuffleArray(arr, num);
        System.out.println("打乱后的华容道：");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
               if(i==num-1&&j==num-1)continue;
               int index1,index2;
               do{
                   index1 = (int) (Math.random() * num);
                   index2 = (int) (Math.random() * num);
               }while((index1==num-1&&index2==num-1)||(index1==i&&index2==j));
                int temp = arr[index1][index2];
                arr[index1][index2] = arr[i][j];
                arr[i][j] = temp;
            }

        }
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if(i==arr.length-1&&j==arr[i].length-1){
                    System.out.print(0);continue;
                }
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}
